package LinkedList;

import Utils.ListNode;

import java.util.ArrayList;
import java.util.List;

public class isPalindromeList {
    public boolean isPalindromeI(ListNode head) {
        if (head == null || head.next == null) {
            return true;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        // 此时链表长度为偶数
        if (fast != null) {
            slow = slow.next;
        }
        cutListNode(head, slow);
        return isEqual(head, reverse(slow));
    }

    private void cutListNode(ListNode head, ListNode slow) {
        while (head.next != slow) {
            head = head.next;
        }
        head.next = null;
    }

    private ListNode reverse(ListNode head) {
        ListNode newHead = null;
        while (head != null) {
            ListNode temp = head.next;
            head.next = newHead;
            newHead = head;
            head = temp;
        }
        return newHead;
    }

    private boolean isEqual(ListNode l1, ListNode l2) {
        while (l1 != null && l2 != null) {
            if (l1.val != l2.val) {
                return false;
            }
            l1 = l1.next;
            l2 = l2.next;
        }
        return true;
    }

    /**
     * 直接将head中的元素存入ArrayList，利用双指针判断ArrayList是否为回文串
     *
     * @author y00520392
     * @since 2020-03-27
     */
    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) {
            return true;
        }
        List<Integer> arrayList = new ArrayList<>();
        while (head != null) {
            arrayList.add(head.val);
            head = head.next;
        }
        return isListPalindrome(arrayList);
    }

    private boolean isListPalindrome(List<Integer> arrayList) {
        int left = 0;
        int right = arrayList.size() - 1;
        while (left < right) {
            // if (arrayList.get(left) != arrayList.get(right)) {
            //     return false;
            // }
            if (!arrayList.get(left).equals(arrayList.get(right))) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}
